//
//  MatterItemView.swift
//  HealthMonitoring
//
//  Created by YTYanK on 20/11/2018.
//  Copyright © 2018 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON

/// 单个组件 -- 重写 MatterItem
class MatterItemView: UIView {

    public enum ItemType: String {
        case label  = "label"  /// 基本label
        case button = "button"
        case dropDown = "dropDown" // 下拉选择菜单  // pikcer 
        case circular = "circular"
        case input = "input"   // 输入框
        case `switch` = "switch" // 滑动
        case radio = "radio"  //单选
        case checkbox = "checkbox" //多选
        case labelArrow = "labelArrow"  //带箭头
        case buttonJump = "buttonJump"
    }

    private var addSubItems = Array<MatterItemView>()
    /// 类型
    private var itemType: ItemType?
    /// 标题
    var title = UILabel()
    /// 横线
    var lineView = UIView()
    var indexPathRow = 0
    /// 唯一标识
    var signID: String?
    /// 选项
    var indexPath: IndexPath?
    /// 数据
    private var json: JSON?
    /// 默认高度
    var matterItemHeight: CGFloat = 44
    var itemData = JSON()
    /// 传值字典
    var itemDictionary: Dictionary<String,Any>?

    /// itemView 当前的 View
    /// type 类型
    /// cellIndex cell 序列号
    /// itemTag 当前view 的 序列号
    /// value 结果值
    /// json: 当前获取到json 数据
    var matterItemBlock: ((_ itemView: MatterItemView, _ type: String, _ cellIndex : Int,  _ itemTag: Int, _ value: String, _ json: JSON)->())?
    //组件单元
    var type_button: UIButton?
    var type_label: UILabel?
    var type_labelArrow: UILabel?
    var type_arrowImg: UIImageView?
    var type_arrowLabel: UILabel?
    var type_moreSelectItemC : UIView?  // 多项的容器
    
    var type_radioBtn1 : UIButton?
    var type_radioBtn2 : UIButton?
    var type_input: UITextField?
    
    init(type: String, json: JSON, frame: CGRect) {
        super.init(frame: frame)
    }
    
    
    init(json: JSON) {
        super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
        
        let type = ItemType.init(rawValue: json["type"].stringValue)!
        self.itemType = type
        self.json = json
        switch type {
        case .label:
            self.addLabelTitle(value: json["title"].stringValue)
            self.initLabel(json)
            break
        case .button:
            self.initButton(json)
            break
        case .labelArrow,
             .buttonJump,
             .dropDown:
            
            self.addLabelTitle(value: json["title"].stringValue)
            self.initLabelArrow(json)
            self.addEvent()
            break
        case .radio:
            self.addLabelTitle(value: json["title"].stringValue)
            self.addItemRadio(json: json)
            break
        case .input:
            self.addLabelTitle(value: json["title"].stringValue)
             self.addItemInput(json: json)
            break
        default: break
            
        }
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 初始化
    func initButton(_ json: JSON) {
        let btn = UIButton()
        self.addSubview(btn)
        self.matterItemHeight = 60.0
        btn.topAlign(view: self)
        btn.leadingAlign(view: self, predicate: "10")
        btn.trailingAlign(view: self, predicate: "-10")
        btn.bottomAlign(view: self)
        btn.setTitle(json["title"].stringValue, for: .normal)
        btn.backgroundColor = json["color"].stringValue == "red" ? .red : .blue
        btn.layer.cornerRadius = 8
        btn.addTarget(self, action: #selector(btnClick), for: UIControlEvents.touchUpInside)
        type_button = btn
    }
    
    func initLabel(_ json: JSON) {
        
        let label = UILabel()
        self.addSubview(label)
        label.centerYAlign(view: self)
        label.trailingAlign(view: self)
        label.heightConstrain(predicate: "\(self.wHeight)")
        label.text = json["value"].stringValue
//        self.backgroundColor = .green
    }
    
    func initLabelArrow(_ json: JSON) {
        //let moreSelectItem = json["itemAry"].arrayValue
        let label = UILabel()
        let img = UIImageView()
        self.addSubview(label)
        self.addSubview(img)
        
        label.centerYAlign(view: self)
        label.heightConstrain(predicate: "44")
        label.text = json["value"].stringValue
        
        
        img.imgName(name: "ringht")
        img.leadingHorizontally(view: label)
        img.centerYAlign(view: self)
        img.widthConstrain(predicate: "10")
        img.heightConstrain(predicate: "20")
        img.trailingAlign(view: self)
//        self.backgroundColor = .red
        type_arrowLabel = label
        type_arrowImg = img
    }

    
    
    /// 添加事件
    func addEvent() {
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapClick))
        self.addGestureRecognizer(tap)
    }
    /// 左标题
    func addLabelTitle(value: String) {
        let label = UILabel()
        self.addSubview(label)
        label.leadingAlign(view: self, predicate: "0")
        label.topAlign(view: self, predicate: "0")
        label.width(view: self, predicate: "*0.3")
        label.heightConstrain(predicate: "44")
        label.text = value
        title = label
        
        self.addLineView()
    }
    
    /// 线条
    func addLineView() {
        let line = UIView()
        self.addSubview(line)
        line.topVertically(view: self.title, predicate: "0")
        line.leadingAlign(view: self, predicate: "0")
        line.trailingAlign(view: self, predicate: "0")
        line.backgroundColor = configure.shareConfigure.HMColor3
        line.heightConstrain(predicate: "1")
        lineView = line
    }
    func addItemRadio(json: JSON) {
        
        let moreSelectItem = json["itemAry"].arrayValue
        let btn1 = UIButton()
        btn1.tag = 0
        
        let btn2 = UIButton()
        btn2.tag = 1
        
        let item1 = moreSelectItem[btn1.tag].dictionaryValue  //只获取两个选择
        let item2 = moreSelectItem[btn2.tag].dictionaryValue
        
        self.addSubview(btn1)
        self.addSubview(btn2)
        
        btn1.centerYAlign(view: self)
        btn1.heightConstrain(predicate: "30")
        btn1.widthConstrain(predicate: "80")
        
        if item1["select"]?.boolValue == true   {
            btn1.setImage(UIImage.init(named: "check_true"), for: .normal)
        }else {
            btn1.setImage(UIImage.init(named: "check_false"), for: .normal)
        }
        btn1.trailingHorizontally(view: btn2)
        btn1.setTitleColor(UIColor.black, for: .normal)
        btn1.setTitle(item1["title"]?.stringValue, for: .normal)
        btn1.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0)
        btn1.addTarget(self, action: #selector(singleSelector), for: UIControlEvents.touchUpInside)
        
        
        btn2.centerYAlign(view: self)
        btn2.heightConstrain(predicate: "30")
        btn2.widthConstrain(predicate: "80")
        
        if item2["select"]?.boolValue == true   {
            btn2.setImage(UIImage.init(named: "check_true"), for: .normal)
        }else {
            btn2.setImage(UIImage.init(named: "check_false"), for: .normal)
        }
        btn2.trailingAlign(view: self)
        btn2.setTitleColor(UIColor.black, for: .normal)
        btn2.setTitle(item2["title"]?.stringValue, for: .normal)
        btn2.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0)
        btn2.addTarget(self, action: #selector(singleSelector), for: UIControlEvents.touchUpInside)
        
        
        type_radioBtn1 = btn1
        type_radioBtn2 = btn2
        
    }
    func addItemInput(json: JSON) {
        let input = UITextField()
        self.addSubview(input)
        
        input.centerYAlign(view: self)
        input.heightConstrain(predicate: "40")
        input.leadingHorizontally(view: title, predicate: "0")
        input.trailingAlign(view: self, predicate: "0")
        input.placeholder = json["placeholder"].stringValue
        let leftView = UIView()
        leftView.widthConstrain(predicate: "30")
        leftView.heightConstrain(predicate: "40")
        input.leftView = leftView
        input.leftViewMode = UITextFieldViewMode.always
        input.text = json["value"].stringValue
        input.delegate = self
        type_input = input
    }
    
    /**
     * 原方法, 提供子项数组,添加多项View选择
     * @param json 数据源
     * @discussion 变更历史： 该方法提供的产生的UI布局不固定，故设置此方法无效。
     */
    func addMoreSelectItem(json: JSON)  {
        let moreSelectItem = json["itemAry"].arrayValue
        var iv = 0
        let cView = UIView() //容器
        self.addSubview(cView)
        
        if addSubItems.count > 0 {
            for itemView in addSubItems {  //全部删除
                itemView.removeFromSuperview()
            }
        }
        for item  in moreSelectItem {
            
            let _type = item["type"].stringValue
            let _title = item["title"].stringValue
            let _time = item["time"].stringValue
            let _isHides = item["isHides"].boolValue
            
            if _isHides == true {
                let itme = MatterItemView.init(type: _type, json: ["title": _title, "value": _time], frame: CGRect.init(x: 0, y: 0, width: self.wWidth, height: 44))
                itme.isUserInteractionEnabled = true
                
                // let strInt = "\(self.tag)\(iv)"
                
                itme.tag = Int(iv)   //itme 序列号
                itme.indexPathRow =  self.indexPathRow // Cell row
                addSubItems.append(itme)
                cView.addSubview(itme)
                //
                let topH =  44  * iv
                itme.topAlign(view: cView, predicate: "\(topH)")
                itme.leadingAlign(view: cView, predicate: "0")
                itme.trailingAlign(view: cView, predicate: "0")
                itme.heightConstrain(predicate: "44")
                itme.matterItemBlock  =  {
                    (subView, subType, subCellInt, subTag, subValue, subJson) -> () in
                   
                    self.matterItemBlock?(subView, subType, self.tag, subTag, self.itemData["value"].stringValue, subJson)
                }
                iv += 1
            }
            
        }
        self.matterItemHeight = CGFloat(iv * 44) + 44.0
        cView.topVertically(view: title, predicate: "0")
        cView.leadingAlign(view: self, predicate: "0")
        cView.trailingAlign(view: self, predicate: "0")
        cView.heightConstrain(predicate: "\(CGFloat(iv * 44))")
        //        cView.backgroundColor = .green
        
        type_moreSelectItemC = cView
    }

    
    
    /*
     事件集
     */
    @objc func btnClick(sender: UIButton) {
        self.matterItemBlock?(self, (self.itemType?.rawValue)!, self.indexPathRow, self.tag, (sender.titleLabel?.text)!, self.itemData)
    }
    @objc func singleSelector(sender: UIButton) {
        self.matterItemBlock?(self, (self.itemType?.rawValue)!, self.indexPathRow, self.tag, "\(sender.tag)", self.itemData)
        
    }
    @objc func tapClick(sender: UITapGestureRecognizer) {
        self.matterItemBlock?(self, (self.itemType?.rawValue)!, self.indexPathRow, self.tag, self.itemData["value"].stringValue, self.itemData)
    }
  
}

extension MatterItemView: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
//        print("\(textField.text)")
        self.matterItemBlock?(self, (self.itemType?.rawValue)!, self.indexPathRow, self.tag, textField.text!, self.itemData)
    }
}
